
import { requestApi } from '../../api';
import { formatImage } from '../../utils/formatImage';
import { extend } from '../../sdk/extend';
import { dateFormat } from '../../utils/dateFormat';
import { logUpload } from '../../utils/logUpload';
const app = getApp();

Page({
    data: {
        channel: 'wx_xcx',
        story: null,
        goodsType: [],
        filterType: [],
        filterName: ['热门', '销量', '最新', '价格', '价格'],
        params: {},
        oid: '',
        goodsTypeInfo: null,
        goodsList: [],
        recomInfo: null,
        start: 0,
        count: 50,
        total: 0,
        isMoreEnd: false, // 加载更多
        isFixed: false,
        isShowStory: false,
        scrollTop: 0, // 筛选成功后，滚动到顶部
        isCoupon: false,  //是否从优惠券跳转过来，请求优惠券可用商品的接口
        isStore: false,  //是否从店铺跳转过来
        isKing: false, //是否从金刚区跳转过来
        isShowFilter: false, // 是否打开筛选
        filterInfo: null, // 筛选条件信息
        bids: '',
        kingTopDetail: null, // 金刚区详情信息
    },
    onLoad: function (options) {
        let params = this.getParams(options)
        let channel = params.channel || 'wx_xcx';

        this.setData({
            channel,
            params,
            isCoupon: Boolean(options.isCoupon),
            isStore: Boolean(options.isStore),
            isKing: Boolean(options.isKing)
        })

        if (params.keywords || options.seller_name) {
            wx.setNavigationBarTitle({ title: `${params.keywords || options.seller_name}` });
        }
        
        this.getSearchGoods();
        this.getFilterAll();
        // 初始化清除已选择的品牌ID
        wx.removeStorageSync('bids');

        // 埋点上报
        let uploadParam = {
            cur_page_entrance_time: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
            cur_page_entrance_type: 1,
            cur_page_resource_id: options.cur_page_resource_id,
            opt_resource_type: options.opt_resource_type || null,
            opt_resource_id: options.opt_resource_id || null,
            opt_resource_area_index: options.opt_resource_area_index || null,
            ref_page_id: options.ref_page_id || null,
            ref_page_resource_id: options.ref_page_resource_id || null,
            ref_opt_resource_id: options.ref_opt_resource_id || null,
            ref_opt_resource_type: options.ref_opt_resource_type || null,
            ref_opt_protocol: options.ref_opt_protocol || null,
            ref_write_sever_timestamp: options.ref_write_sever_timestamp || null,
            log_type: options.log_type || null,
        }

        if(options.isKing) {
            uploadParam['cur_page_id'] = 'OFGoodsFlowGoodslndexViewController';
            uploadParam['opt_resource_area'] = 119;
            logUpload.handleUpload(uploadParam)
        } else if (options.isSearch) {
            uploadParam['cur_page_id'] = 'OFGoodsFlowViewController20';
            uploadParam['opt_resource_area'] = options.isSearch;
            logUpload.handleUpload(uploadParam)
        }
    },
    //  商品品牌页搜索
    getSearchGoods() {
        let { params, goodsList, oid, goodsTypeInfo, start, count, isCoupon, isStore, isKing } = this.data;
        const info  = extend(true, {}, params, { oid, start: start * count, count, is_new_ver: true });
        let url = requestApi.searchGoods;
        wx.showLoading({
            title: '加载中...',
        });

        if (isCoupon) {
            url = requestApi.allCouponGoodsList;
        }

        if (isKing) {
            url = requestApi.kingTop;
        }

        if (goodsTypeInfo) {
            switch (String(goodsTypeInfo.type)) {
                case '1':
                    info['goods_type_id'] = goodsTypeInfo.id;
                    break;
                case '2':
                    info['brand_id'] = goodsTypeInfo.id;
            }
        }

        if (start == 0) {
            goodsList = [];
        }

        app.request({
            url: url,
            data: info
        }, (d) => {
            if (d.original.ret_code == 200) {
                const info = d.original.data;
                // 商品列表
                let lists = [], filtrate = [], filterList = [], brandStory = null, recom = null, kingInfo = null, oidNum = oid;
                info.item_list.forEach(item => {
                    if (item.type == 31) {
                        brandStory = item.data;
                        brandStory.big_image.full_path = formatImage.cdnImage(brandStory.big_image.path, formatImage.THUMBNAIL_M);
                    } else if (item.type == 33) {
                        filterList = item.data.order || item.data.orders;
                        oidNum = item.data.selected_oid_default || '3';
                    } else if (item.type == 34) {
                        item.data.product_cover_image.full_path = formatImage.cdnImage(item.data.product_cover_image.path, formatImage.THUMBNAIL_M);
                        if (!goodsList.find(i => i.gid == item.data.gid)) {
                            lists.push(item.data);
                        }
                    } else if (item.type == 41) {
                        recom = item.data;
                    } else if (item.type == 931 && !isStore) {
                        filtrate = item.data.filtrate;
                    } else if (item.type == 152) {
                        item.data.cover_image.full_path = formatImage.cdnImage(item.data.cover_image.path, formatImage.THUMBNAIL_M);
                        kingInfo = item.data;
                    }
                });

                if (start) {
                    lists = [].concat(goodsList, lists)
                } else {
                    if (!goodsTypeInfo) {
                        const setParams = {};

                        if (filtrate.length) {
                            setParams['goodsType'] = filtrate;
                        }
                        if (filterList.length) {
                            setParams['filterType'] = filterList;
                        }
                        if (info.total) {
                            setParams['total'] = info.total;
                        }
                        if (brandStory) {
                            setParams['story'] = brandStory;
                        }

                        if (kingInfo) {
                            setParams['kingTopDetail'] = kingInfo;
                        }

                        setParams['goodsTypeInfo'] = filtrate[0];

                        this.setData(setParams);
                    }

                    if (params.keywords || info.title) {
                        wx.setNavigationBarTitle({ title: `${params.keywords || info.title}(${info.total})` });
                    } else if (isKing) {
                        wx.setNavigationBarTitle({ title: `${kingInfo.title}` });
                    }
                }
                
                this.setData({
                    goodsList: lists,
                    start: start + 1,
                    recomInfo: recom,
                    oid: oidNum,
                    isMoreEnd: (lists.length >= info.total)
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            wx.hideLoading();
        })
    },
    getFilterAll() {
        const { params, isKing } = this.data;
        const type = !isKing ? 1 : 2;

        app.request({
            url: requestApi.searchGoodsFilterAll,
            data: {
                params_info: JSON.stringify(params),
                type,
                is_new_ver: true
            }
        }, (d) => {
            if (d.original.ret_code == 200) {
                this.setData({
                    filterInfo: d.original.data
                });

                app.data.searchBrands = d.original.data.brands.map(item => {
                    return {
                        bid: item.bid,
                        name_e: item.brandname_e,
                        name_c: item.brandname_c,
                    }
                });
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            wx.hideLoading();
        })
    },
    // 商品筛选
    chooseFilterType(e) {
        let { filterType, oid, isFixed } = this.data;
        const { index } = e.currentTarget.dataset;

        if (index < 3) {
            oid = filterType[index].oid;
        } else {
            oid = oid > 2 ? 2 : ( oid == 2 ? 1 : 2);
        }

        this.setData({
            oid,
            start: 0
        });
        
        if (isFixed) {
            this.setData({
                scrollTop: '460rpx',
            });
        }

        this.getSearchGoods();
    },
    // 商品类别
    chooseGoodsType(e) {
        const { info } = e.currentTarget.dataset;

        this.setData({
            goodsTypeInfo: info,
            start: 0
        })

        this.getSearchGoods();
    },
    jumpStory() {
        const { story } = this.data;

        wx.navigateTo({
            url: `/pages/webView/webView?bid=${story.bid}&type=story`,
        })
    },
    loadMore() {
        const { isMoreEnd } = this.data;

        if (!isMoreEnd) {
            this.getSearchGoods();
        }
    },
    pageScroll(e) {
        const { isFixed } = this.data;

        if (e.detail.scrollTop >= (134 + 54 + 54)) {
            if (!isFixed) {
                this.setData({
                    isFixed: true
                })
            }
        } else {
            if (isFixed) {
                this.setData({
                    isFixed: false
                })
            }
        }
    },
    getParams(options) {
        var params = {}

        if (options.keywords) {
            params.keywords = options.keywords
        } else {
            params.keywords = ''
        }

        if (options.tag_search) {
            params.tag_search = options.tag_search
        }

        if (options.brand_id) {
            params.brand_id = options.brand_id
            params.brand_value = options.brand_value
        }

        if (options.price_id) {
            params.price_id = options.price_id
        }

        if (options.gender_id) {
            params.gender_id = options.gender_id
        }

        if (options.goods_type_id) {
            params.goods_type_id = options.goods_type_id
        }

        if (options.goods_type_value) {
            params.goods_type_value = options.goods_type_value
        }

        if (options.goods_channel_source) {
            params.goods_channel_source = options.goods_channel_source
        }

        if (options.seller_uid) {
            params.seller_uid = options.seller_uid
        }
        
        if (options.coupon_no) {
            params.coupon_no = options.coupon_no
        }

        if (options.isKing) {
            params.page_index_id = options.tid
        }

        return params
    },
    openFilter() {
        if (this.data.filterInfo.total) {
            this.setData({
                isShowFilter: true
            })
        }
    },
    onEnter() {

    },
    getFilterList(e){
        const params = e.detail;
        this.setData({
            isShowFilter: false,
            start: 0,
            goodsTypeInfo: null,
            scrollTop: 0,
            params
        })
        
        this.getSearchGoods();
    },
    // 关注与取消关注
    foucusHandler() {
        const { story } = this.data;

        app.request({
            url: requestApi.foucsBrand,
            method: 'POST',
            data: {
                operations: JSON.stringify([{ "brand_id": story.bid, "is_favorite": !story.is_favorite }])
            }
        }, (d) => {
            if (d.original.ret_code == 200) {
                const str = `story.is_favorite`;

                if(!story.is_favorite) {
                    wx.showToast({
                        title: '关注成功！可在关注页面随时了解此品牌商品更新动态。',
                        icon: 'none',
                        duration: 2000
                    })
                }

                this.setData({
                    [str]: !story.is_favorite
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
        })
    },
    recomTag(e) {
        const { name } = e.currentTarget.dataset;

        wx.navigateTo({
            url: '/pages/categoryHall/categoryHall?keywords=' + name,
        });
    }
})